package com.flying.fish.gateway.listener;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.client.config.listener.impl.PropertiesListener;
import com.flying.fish.gateway.service.ConfigRefreshService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * @Description nacos动态监听器，当dataId的内容发生变更后，自动刷新配置
 * @Author JL
 * @Date 2022/11/1
 * @Version V1.0
 */
@Component
public class NacosDataListener implements ApplicationRunner {

    static Logger log = LoggerFactory.getLogger(NacosDataListener.class);

    @Resource
    private NacosConfigProperties nacosConfigProperties;

    @Resource
    private ConfigRefreshService configRefreshService;

    @Override
    public void run(ApplicationArguments args) {
        String serverAddr = nacosConfigProperties.getServerAddr();
        String dataId = nacosConfigProperties.getPrefix() + "." + nacosConfigProperties.getFileExtension();
        String group = nacosConfigProperties.getGroup();
        log.info("run nacos listener server, dataId:{}, group:{}, type:{}", dataId, group, nacosConfigProperties.getFileExtension());
        try {
            ConfigService configService = NacosFactory.createConfigService(serverAddr);
            configService.addListener(dataId, group, new PropertiesListener() {

                @Override
                public void innerReceive(Properties properties) {
                    log.info("listener news context：\n{}", properties);
                    //当nacos获取到配置变更监听后，更新gateway网关
                    String gatewayConfig = (String) properties.get("gateway");
                    // 更新网关路由
                    if (StringUtils.isNotBlank(gatewayConfig)){
                        log.info("Refresh gatewayConfig changed: " + gatewayConfig);
                        configRefreshService.setGatewayConfig(gatewayConfig);
                        log.info("Refresh gatewayConfig changed success!");
                    }
                }
            });
        }catch(Exception e){
            e.printStackTrace();
            log.error("load nacos listener data error, msg:{}" + e.getMessage(), e);
        }
    }

}
